package com.changgou.oauth.config;

import com.changgou.oauth.util.JwtToken;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 * @author ：hushengjin
 */
@Configuration
public class FeignOauth2RequestInterceptor implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate requestTemplate) {
        try {
            //创建令牌信息
            String token = "bearer " + JwtToken.adminJwt();
            //将令牌添加到头文件
            requestTemplate.header("Authorization", token);
            //使用RequestContextHolder工具获取request相关变量
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (attributes != null) {
                HttpServletRequest request = attributes.getRequest();
                //获取头信息
                Enumeration<String> requestHeaderNames = request.getHeaderNames();
                if (requestHeaderNames != null) {
                    while (requestHeaderNames.hasMoreElements()) {
                        //头文件的key
                        String name = requestHeaderNames.nextElement();
                        //头文件的value
                        String value = request.getHeader(name);
                        requestTemplate.header(name, value);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
